import React, { useState } from 'react';
import { Form, Button, Input, Modal } from 'antd';

import { KInstanceClone } from '../data.d';

export interface CloneFormProps {
  onCancel: (flag?: boolean, formVals?: KInstanceClone) => void;
  onSubmit: (values: KInstanceClone) => void;
  cloneModalVisible: boolean;
  values: KInstanceClone;
}
const FormItem = Form.Item;

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const CloneForm: React.FC<CloneFormProps> = (props) => {
  const [formValues, setFormValues] = useState<KInstanceClone>({
    oldName: props.values.oldName,
    newName: props.values.newName,
    description: props.values.description,
  });

  const [form] = Form.useForm();

  const {
    onSubmit: handleClone,
    onCancel: handleCloneModalVisible,
    cloneModalVisible,
    values,
  } = props;

  const handleRealClone = async () => {
    const fieldsValue = await form.validateFields();
    setFormValues({ ...formValues, ...fieldsValue });
    handleClone({ ...formValues, ...fieldsValue });
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => handleCloneModalVisible(false, values)}>取消</Button>
        <Button type="primary" onClick={() => handleRealClone()}>克隆</Button>
      </>
    );
  };

  return (
    <Modal
      width={640}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="克隆环境"
      visible={cloneModalVisible}
      footer={renderFooter()}
      onCancel={() => handleCloneModalVisible()}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          oldName: formValues.oldName,
          newName: formValues.newName,
          description: formValues.description,
        }}
      >
        <FormItem
          name="oldName"
          label="被克隆环境"
        >
          <Input placeholder="请输入" />
        </FormItem>
        <FormItem
          name="newName"
          label="新环境"
          rules={[{ required: true, message: '请输入新环境名称'}]}
        >
          <Input placeholder="请输入"/>
        </FormItem>
        <FormItem
          name="description"
          label="新环境描述"
          rules={[{ required: true, message: '新环境的描述'}]}
        >
          <Input placeholder="请输入" />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default CloneForm;
